﻿namespace Digitalmes.Application.Sys.Users.Commands;

/// <summary>
/// 重置用户密码命令。
/// </summary>
/// <param name="UserId"></param>
/// <param name="NewPassword"></param>
public record ResetPasswordCommand(long UserId, string NewPassword) : IRequest<IResult<bool>>;

internal sealed class ResetPasswordCommandHandler(IRepository<SysUser> repo) : IRequestHandler<ResetPasswordCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await repo.GetByIdAsync(request.UserId, cancellationToken);
        if (user == null)
        {
            return Result.Failure("用户不存在");
        }

        // 对明文密码进行MD5处理
        user.Password = CryptoUtils.MDString(user.Password);
        var ok = await repo.UpdateAsync(user, m => new
        {
            m.Password,
            m.LastModifiedBy,
            m.LastModifiedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
